module.exports = function (app, models, $, db, nm) {
  //用户获取商品详情
  app.get("/product", (req, res) => {
    if (req.query.productId) {
      models.product.find(
        { _id: req.query.productId },
        (ret) => {
          if(!ret.errorMsg){
            models.sku.list({ productId: req.query.productId },
              (skus) => {
                ret.skus = skus;
                res.send(ret);
              }
            );
          }else{
            res.send(ret);
          }
        }
      );
    } else {
      res.send({ errorMsg: "请传入productId" });
    } 
  });

  function productsRouter(req,res){
    let sql = `
    (select max(_id) as maxId,productId from sku group by productId) as maxSku
    left join sku on sku.productId = maxSku.productId and maxSku.maxId = sku._id
    left join product on product._id = sku.productId
    where sku.state = 1 and product.state = 1 and product.status = 1 and product.functionality != 1`
    ///商品ID
    if(req.query.productIds) sql += ` and product._id in(${req.query.productIds})`
    ///品牌ID
    if(req.query.brandIds) sql += ` and product.brandId in(${req.query.brandIds})`
    ///名称关键字
    if(req.query.key) sql += ` and product.name like '%${req.query.key}%'`
    if(req.query.sorted == 1){//按销量降序
      sql += ` order by product.sales desc`
    }else if(req.query.sorted == 2){//按售价升序
      sql += ` order by sku.salePrice`
    }else if(req.query.sorted == 3){//按售价降序
      sql += ` order by sku.salePrice desc`
    }else{//默认 按时间降序
      sql += ` order by product.createTime desc`
    }
    ///查询总数
    db._eval(`select count(*) as total from ` + sql,ret => {
      if(ret.errorMsg){
        res.send(ret);
      }else{
        var total = ret[0].total;
        req.query.pageSize = req.query.pageSize || 10
        req.query.pageNum = req.query.pageNum || 1
        let offset = req.query.pageSize * (req.query.pageNum - 1)
        db._eval(`
        select sku.productId,sku.skuId,sku.salePrice,sku.originalPrice,sku.props,product.name as productName,product.imgs as productImgs,product.sales 
        from
        ${sql} limit ${req.query.pageSize} offset ${offset}`,ret => {
          if(ret.errorMsg){
            res.send(ret);
          }else{
            res.send({total, rows:ret});
          }
        })
      }
    })
  }
  //用户搜索商品(分类，商品名称，销量，品牌) 
  app.get('/products',function(req,res,next){
    var categoryQuery = { state:1 };
    if(req.query.key) {
      req.query.key = decodeURIComponent(req.query.key);
      categoryQuery.name = {$regex: req.query.key};
    }
    models.category_product.list({},function(ret){
      if(!ret.errorMsg){
        var productIds = [];
        for(var i = 0; i < ret.length; i ++) productIds.push(ret[i].productId);
        if(productIds.length) {
          req.query.productIds = productIds.join(',');
          req.query.key = undefined
        }
        next();
      }else{
        res.send(ret);
      }
    },{
      join:{
        categoryId:{
          name:'category',
          key:'id',
          query:categoryQuery
        }
      }
    })
  },productsRouter)
};
